


<script lang="ts" setup>
// Api增删改查接口
import { addData, findPage, remove, updateData, search } from "@@/apis/trade/TradeUserWishApis";
// Http请求全局参数数据类型
import {PageParam, SearchSortPageParam} from "@@/types/http";
// Http请求专用参数和请求结果数据类型
import {
	TradeUserWishCreateOrUpdateParam,
	TradeUserWishSearchParam,
	TradeUserWishOrderParam,
	type TradeUserWishResult
} from "@/types/TradeUserWish";
// 分页组件
import { usePagination } from "@@/composables/usePagination";

// Element-plus图标类型
import { CirclePlus, Delete, Download, Refresh, RefreshRight, Search, } from "@element-plus/icons-vue";
// Element-plus数据类型
import type { FormInstance, FormRules, UploadFile, UploadProps, UploadRawFile } from "element-plus";
// 深度拷贝函数
import { cloneDeep } from "lodash-es";
// 导出excel的函数
import { export_json_to_excel } from "@/common/utils/excel/Export2Excel.js";

defineOptions({
	// 命名当前组件
	name: "TradeUserWish",
});

// 列表加载状态
const loading = ref<boolean>(false);
// 导出动画状态
const downloadLoading = ref<boolean>(false);
// 分页数据
const {paginationData, handleCurrentChange, handleSizeChange} = usePagination();
// 默认表单数据
const DEFAULT_FORM_DATA: TradeUserWishCreateOrUpdateParam = {
	id: -1,
			accountCode: 0,
			cateCode: 0,
			cateLabel: '',
			goodsWords: '',
			addressWords: '',
			time: 0,
			expireTime: 0,
};

// 列表数据
const tableData = ref<{ data: TradeUserWishResult[] }>({
  data: [],
});

// 对话框显示开关
const dialogVisible = ref<boolean>(false);
// 表单数据
const formRef = ref<FormInstance | null>(null);
// 表单数据 深拷贝默认数据
const formData = ref<TradeUserWishCreateOrUpdateParam>(cloneDeep(DEFAULT_FORM_DATA));
// 表单校验规则
const formRules: FormRules<TradeUserWishCreateOrUpdateParam> = {
	// title: [{ required: true, trigger: "blur", message: "请输入标题" }],
	// ...
};

// #region 增删改查
/**
* 新增或者修改
*/
function handleCreateOrUpdate() {
	// 表单校验
	formRef.value?.validate((valid: any) => {
		if (!valid) {
			ElMessage.error("表单校验不通过");
		return;
	}
	// 显示加载框
	loading.value = true;
	// 判断是否有id,以此确定是新增还是修改
	let isCreate = formData.value.id === undefined || formData.value.id === null || formData.value.id === -1;
	// 默认修改
	let callCreateOrUpdateApi = updateData
	let createOrUpdate = "修改";
	// 如果是新增，修改数据
	if(isCreate){
		callCreateOrUpdateApi = addData;
		createOrUpdate = "新增";
	}

	// 重构参数
	let param = new TradeUserWishCreateOrUpdateParam(
				Number(formData.value.id),
				Number(formData.value.accountCode),
				Number(formData.value.cateCode),
				formData.value.cateLabel,
				formData.value.goodsWords,
				formData.value.addressWords,
				Number(formData.value.time),
				Number(formData.value.expireTime),

	)
	
	// 调用接口
	callCreateOrUpdateApi(param)
		// 请求成功 res为数据结构 NetResult(code,msg,data)
		.then(({data}) => {
			// 判断是否成功
			const isSuccess = data.value;
			console.log(isSuccess);
			if (isSuccess) {
				// 提示成功
				ElMessage.success("数据" + createOrUpdate + "操作成功");
				// 关闭对话框
				dialogVisible.value = false;
				// 查询分页数据
				handleFindPage();
			}
			})
			.finally(() => {
				// 关闭加载框
				loading.value = false;
		});
	});
}

/**
* 删除
* @param row
*/
function handleRemove(row: TradeUserWishResult) {
	ElMessageBox.confirm(`正在删除数据：${row.id}，确认删除？`, "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(() => {
		// 调用接口
		remove({id: row.id}).then(() => {
			ElMessage.success("删除成功");
			// 查询分页数据
			handleFindPage();
		});
	});
}

/**
* 修改
* @param row
*/
function handleUpdate(row: TradeUserWishResult) {
	// 弹出对话框
	dialogVisible.value = true;
	// 深拷贝 当前行数据
	formData.value = cloneDeep(row);
	// 待实现
}

/**
* 分页查询
*/
function handleFindPage() {
	loading.value = true;
	const page = paginationData.currentPage;
	const pageSize = paginationData.pageSize;
	const body = new PageParam(page, pageSize);
	// 调用接口
	findPage(body)
		.then(({data}) => {
			// 设置数据池总数
			paginationData.total = data.total;
			// 设置表格数据
			tableData.value.data = data.dataList;
		})
		.catch(() => {
			// 表格数据置空
			tableData.value.data = [];
		})
		.finally(() => {
			// 关闭加载框
			loading.value = false;
	});
}

// #endregion

// 搜索
const searchFormRef = ref<FormInstance | null>(null);
// 搜索表单数据
const searchData = reactive<TradeUserWishSearchParam>(new TradeUserWishSearchParam());

// 处理搜索
function handleSearch() {
	if (paginationData.currentPage === 1) {
		callSearchApi();
	} else {
		paginationData.currentPage = 1;
	}
}

// 调用搜索接口
function callSearchApi() {
	loading.value = true;
	const page = paginationData.currentPage;
	const pageSize = paginationData.pageSize;

	const body: SearchSortPageParam<TradeUserWishSearchParam, TradeUserWishOrderParam> = new SearchSortPageParam(
		new PageParam(page, pageSize),
		searchData,
		new TradeUserWishOrderParam(0, 0, 0, 0, 0, 0, 0, 0, 0, )
	)

	// 调用接口
	search(body)
		.then(({data}) => {
			// 设置数据池总数
			paginationData.total = data.total;
			// 设置表格数据
			tableData.value.data = data.dataList;
		})
		.catch(() => {
			// 表格数据置空
			tableData.value.data = [];
		})
		.finally(() => {
			// 关闭加载框
			loading.value = false;
		});
}

// 重置搜索表单
function resetSearch() {
	searchFormRef.value?.resetFields();
	handleSearch();
}

// #region 上传图片
const imageUrl = ref("");

const uploadRef = ref(null);

// 上传图片成功后的回调函数
const handleUploadSuccess: UploadProps["onSuccess"] = (response: any, uploadFile: UploadFile) => {
	imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};

// 上传图片前的校验
const beforeUpload: UploadProps["beforeUpload"] = (rawFile: UploadRawFile) => {
	if (rawFile.type !== "image/jpeg") {
		ElMessage.error("Avatar picture must be JPG format!");
		return false;
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error("Avatar picture size can not exceed 2MB!");
		return false;
	}
	return true;
};

// 重置表单
function resetForm() {
	formRef.value?.clearValidate();
	console.log("DEFAULT_FORM_DATA", DEFAULT_FORM_DATA);
	formData.value = cloneDeep(DEFAULT_FORM_DATA);
}
// #endregion

// region 导出excel
// 导出excel
function exportToExcel() {
	downloadLoading.value = true;
	const title = '心愿列表';
	const tHeader = [
		'ID',
		'用户账号',
		'商品分类编码',
		'商品分类标签',
		'商品匹配关键词',
		'地址匹配关键词',
		'创建时间',
		'过期时间',
		'数据状态',
	];
	const filtervals = [
			'id',
			'accountCode',
			'cateCode',
			'cateLabel',
			'goodsWords',
			'addressWords',
			'time',
			'expireTime',
			'status',
	];
	const data=formatJson(filtervals,tableData.value.data);
		export_json_to_excel({
		header: tHeader,
		data,
		filename: title
	} as ExcelExportData & Parameters<typeof export_json_to_excel>[0])
	downloadLoading.value = false;
}

// 格式化json
function formatJson(filterVal:Array<any>, jsonData:Array<any>) {
	return jsonData.map(v => filterVal.map(j => v[j]))
}

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], handleFindPage, {
		immediate: true,
});
</script>

<template>
	<div class="app-container">
		<!--搜索表单-->
		<el-card v-loading="loading" shadow="never" class="search-wrapper">
			<el-form ref="searchFormRef" :inline="true" :model="searchData">
				<el-form-item prop="accountCode" label="用户账号">
						<el-input v-model="searchData.accountCode" placeholder="请输入用户账号..."/>
				</el-form-item>
				<el-form-item prop="cateCode" label="商品分类编码">
						<el-input v-model="searchData.cateCode" placeholder="请输入商品分类编码..."/>
				</el-form-item>
				<el-form-item prop="cateLabel" label="商品分类标签">
						<el-input v-model="searchData.cateLabel" placeholder="请输入商品分类标签..."/>
				</el-form-item>
				<el-form-item prop="goodsWords" label="商品匹配关键词">
						<el-input v-model="searchData.goodsWords" placeholder="请输入商品匹配关键词..."/>
				</el-form-item>
				<el-form-item prop="addressWords" label="地址匹配关键词">
						<el-input v-model="searchData.addressWords" placeholder="请输入地址匹配关键词..."/>
				</el-form-item>
				<el-form-item prop="time" label="创建时间">
						<el-input v-model="searchData.time" placeholder="请输入创建时间..."/>
				</el-form-item>
				<el-form-item prop="expireTime" label="过期时间">
						<el-input v-model="searchData.expireTime" placeholder="请输入过期时间..."/>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" :icon="Search" @click="handleSearch">
							查询
					</el-button>
					<el-button :icon="Refresh" @click="resetSearch">
							重置
					</el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<!--表格操作栏-->
		<el-card v-loading="loading" shadow="never">
			<!--表格操作条-->
			<div class="toolbar-wrapper">
				<div>
					<el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">
						新增
					</el-button>
					<el-button type="danger" :icon="Delete">
						批量删除
					</el-button>
				</div>
				<div>
					<el-tooltip content="下载">
						<el-button type="primary" :icon="Download" @click="exportToExcel" circle/>
					</el-tooltip>
					<el-tooltip content="刷新当前页">
						<el-button type="primary" :icon="RefreshRight" circle @click="handleFindPage"/>
					</el-tooltip>
				</div>
			</div>

			<!--表格-->
			<div class="table-wrapper">
				<el-table :data="tableData.data">
        	<el-table-column prop="accountCode" label="用户账号" align="center"/>
        	<el-table-column prop="cateCode" label="商品分类编码" align="center"/>
        	<el-table-column prop="cateLabel" label="商品分类标签" align="center"/>
        	<el-table-column prop="goodsWords" label="商品匹配关键词" align="center"/>
        	<el-table-column prop="addressWords" label="地址匹配关键词" align="center"/>
        	<el-table-column prop="time" label="创建时间" align="center"/>
        	<el-table-column prop="expireTime" label="过期时间" align="center"/>
					<el-table-column prop="status" label="数据状态" align="center">
						<template #default="scope">
							<el-tag
								v-if="scope.row.status === 0"
								type="success"
								effect="plain"
								disable-transitions>
								正常
							</el-tag>
							<el-tag v-else type="danger" effect="plain" disable-transitions>
								已删除
							</el-tag>
						</template>
					</el-table-column>

					<el-table-column fixed="right" label="操作" width="150" align="center">
						<template #default="scope">
							<el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">
								修改
							</el-button>
							<el-button type="danger" text bg size="small" @click="handleRemove(scope.row)">
								删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<!-- 分页条 -->
			<div class="pager-wrapper">
				<el-pagination
					background
					:layout="paginationData.layout"
					:page-sizes="paginationData.pageSizes"
					:total="paginationData.total"
					:page-size="paginationData.pageSize"
					:current-page="paginationData.currentPage"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"/>
			</div>
		</el-card>

		<!-- 新增和修改对话框 -->
		<el-dialog
			v-model="dialogVisible"
			:title="formData.id === null || formData.id === undefined || formData.id === -1 ? '新增心愿' : '修改心愿'"
			width="30%"
			@closed="resetForm"
			destroy-on-close>
			<el-form
				ref="formRef"
				:model="formData"
				:rules="formRules"
				label-width="100px"
				label-position="left">
				<el-form-item prop="accountCode" label="用户账号">
						<el-input v-model="formData.accountCode" placeholder="请输入用户账号..."/>
				</el-form-item>
				<el-form-item prop="cateCode" label="商品分类编码">
						<el-input v-model="formData.cateCode" placeholder="请输入商品分类编码..."/>
				</el-form-item>
				<el-form-item prop="cateLabel" label="商品分类标签">
						<el-input v-model="formData.cateLabel" placeholder="请输入商品分类标签..."/>
				</el-form-item>
				<el-form-item prop="goodsWords" label="商品匹配关键词">
						<el-input v-model="formData.goodsWords" placeholder="请输入商品匹配关键词..."/>
				</el-form-item>
				<el-form-item prop="addressWords" label="地址匹配关键词">
						<el-input v-model="formData.addressWords" placeholder="请输入地址匹配关键词..."/>
				</el-form-item>
				<el-form-item prop="time" label="创建时间">
						<el-input v-model="formData.time" placeholder="请输入创建时间..."/>
				</el-form-item>
				<el-form-item prop="expireTime" label="过期时间">
						<el-input v-model="formData.expireTime" placeholder="请输入过期时间..."/>
				</el-form-item>
			</el-form>

			<template #footer>
				<el-button @click="dialogVisible = false">
					取消
				</el-button>
				<el-button type="primary" :loading="loading" @click="handleCreateOrUpdate">
					确认
				</el-button>
			</template>
		</el-dialog>
	</div>
</template>

// 页面宏样式
<style lang="scss" scoped="scoped">
    .search-wrapper {
        margin-bottom: 20px;

        :deep(.el-card__body) {
            padding-bottom: 2px;
        }
    }

    .toolbar-wrapper {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
    }

    .table-wrapper {
        margin-bottom: 20px;
    }

    .pager-wrapper {
        display: flex;
        justify-content: flex-end;
    }

    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
